package ar.uba.fi.RSACryptoFiuba.model.keygeneration;

import ar.uba.fi.RSACryptoFiuba.model.InvalidValueException;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;


public class CalculateEStep extends RSAStep {
	
	@Override
	public void execute(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer d = Integer.valueOf(keyGenerationMessage.getD());
		Integer phi = Integer.valueOf(keyGenerationMessage.getPhi());
        Integer e = RSACalculator.getModMultiplicativeInverse(d, phi);
        keyGenerationMessage.setE(e.toString());
	}
	
	@Override
	public void undo(RSAMessage message) {
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		keyGenerationMessage.setE("");
	}

	@Override
	public void test(RSAMessage message) {
		String element = message.getElementToEvaluate();
		verifyNumericalValue(element);
		RSAKeyGenerationMessage keyGenerationMessage = (RSAKeyGenerationMessage) message;
		Integer d = Integer.valueOf(keyGenerationMessage.getD());
		Integer phi = Integer.valueOf(keyGenerationMessage.getPhi());
        Integer e = RSACalculator.getModMultiplicativeInverse(d, phi);        		
		boolean isValid = String.valueOf(e).equals(element);
		if(!isValid){
			throw new InvalidValueException("El número d debe ser el inverso multiplicativo de d en módulo phi.");
		}
		keyGenerationMessage.setE(element);
	}

}
